#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <fcntl.h>
#include <sys/ioctl.h>

int mdsend_command_and_get_nresponses(int fd_server_socket, char *command, char **response, int number){
  int len = 1;
  fd_set input_fd_set;
  int max_fd;
  int result;
  int nread;
  char *received;
  char *kde;
  int i;
  
  FD_ZERO(&input_fd_set);
  FD_SET(fd_server_socket, &input_fd_set);
  max_fd = fd_server_socket + 1;
  
  len = strlen(command);
  if (write(fd_server_socket, command, len) != len)
  {
    fprintf(stderr, "vyslanie commandu na mdemon zlyahlo\n");
    return -1;
  }
  
  fsync(fd_server_socket);
  *response = malloc(sizeof(char));
  (*response)[0] = '\0';
  kde = *response;
  int cislo = number;
  while(number > 0)
  {
    result = select(max_fd, &input_fd_set, NULL, NULL, NULL);
    if (result == -1)
    {
      //perror("send_command_and_get_response:");
      return -1;
    }
    if (FD_ISSET(fd_server_socket, &input_fd_set))
    {
      
      ioctl(fd_server_socket, FIONREAD, &nread);
      if (nread == 0)
      {
	fprintf(stderr, "connection to mdemon lost\n");
	close(fd_server_socket);
	return -1;
      }
      
      received = (char *) malloc((nread+2)*sizeof(char));
      if (read(fd_server_socket, received, nread) == nread)
      {
	received[nread] = '\0';	
	//printf("received=|%s|", received);
	*response = realloc( (*response), (len+nread+3)*sizeof(char));
	*response = strncat((*response), received, (nread+1));
	len += nread+1; 
	//printf("response=|%s|\n", (*response));
	number = cislo;
	kde = (*response);
	while ((kde = strchr(kde, '\n')) != NULL)
	{
	  number--;
	  kde  = kde + sizeof(char);
	}
	//printf("received %d pocet znakov:%s\n", nread, received);
      }     
      free(received);
      received = NULL;
    }
    else
    {
      FD_SET(fd_server_socket, &input_fd_set); // bola by sranda keby toto niekedy nastalo
    } 
  }
  return 0;
  
}